import React, { useState, useEffect, useRef } from 'react';
import { Button, message } from 'antd';
import ProForm, {
  ModalForm,
  ProFormText,
  ProFormDependency,
  ProFormSelect,
} from '@ant-design/pro-form';
import { PlusOutlined } from '@ant-design/icons';
import { request } from 'umi';
import type { ProFormInstance } from '@ant-design/pro-form';
import dayjs from 'dayjs';
import { api } from '@/global';
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default (props: any) => {
  const [prenode, SetPreNode] = useState<any[]>();
  const [classesInfo, setClassesInfo] = useState<any[]>();
  const formRef = useRef<ProFormInstance>();
  useEffect(() => {
    async function getNodeData() {
      const data = await request(api.getProfessionalByDeptId);
      const result = await request(api.getClassesList);
      SetPreNode(data.data);
      setClassesInfo(result.data);
    }

    getNodeData();
  }, []);

  const getClassesList = (id: number) => {
    const temp = classesInfo;

    const data = temp
      ?.filter((item) => item.professionalId === id)
      .map((item) => {
        return {
          label: item.className,
          value: item.id,
        };
      });

    return data;
  };

  const changeNode = (id: number) => {
    const temp = prenode;

    const data = temp
      ?.filter((item) => item.deptId === id)
      .map((item) => {
        return {
          label: item.professionalName,
          value: item.id,
        };
      });

    return data;
  };

  return (
    <ModalForm<{
      name: string;
      company: string;
    }>
      formRef={formRef}
      title="创建课程"
      trigger={
        <Button type="primary">
          <PlusOutlined />
          创建课程
        </Button>
      }
      autoFocusFirstInput
      modalProps={{
        onCancel: () => console.log('run'),
      }}
      onFinish={async (values) => {
        await waitTime(2000);

        const data = values?.classes.map((item) => {
          return item.value;
        });
        values.classes = JSON.stringify(data);

        const result = await request(api.insertOrUpdateCourseInfo, {
          method: 'POST',
          data: {
            ...values,
          },
        });

        if (result.success) {
          message.info('保存成功');
          props.reloadPage();
          formRef.current?.resetFields();
        } else {
          message.info('保存失败');
        }

        return true;
      }}
    >
      <ProForm.Group>
        <ProFormText
          width="md"
          tooltip="年级+系部+专业+课程名称"
          name="courseName"
          label="课程名称"
          placeholder="请输入名称"
          rules={[
            {
              required: true,
              message: '请输入名称',
            },
          ]}
        />
        <ProFormText
          width="sm"
          tooltip="如果没有可以不填写"
          name="courseCode"
          label="课程名称"
          placeholder="请输入课程代号"
        />
        <ProFormSelect
          request={async () => {
            const { data } = await request(api.getEarlyYear, {});

            let year = dayjs().year();

            const list: any[] = [];

            while (year - 2000 - data >= 0) {
              list.push({
                label: String(year - 2000) + '级',
                value: year - 2000,
              });
              year = year - 1;
            }

            return list;
          }}
          width="xs"
          name="courseGrade"
          rules={[
            {
              required: true,
              message: '请选择年级',
            },
          ]}
          label="年级"
          placeholder="请选择年级"
        />
      </ProForm.Group>

      <ProForm.Group>
        <ProFormSelect
          onMetaChange={(item) => {
            console.log(item);
          }}
          request={async () => {
            const deptData = await request(api.getAllDept, {});
            const list: any[] = [];
            deptData.data.map((item: any) => {
              list.push({
                label: item.deptName,
                value: item.id,
              });
            });

            return list;
          }}
          width="sm"
          name="deptName"
          rules={[
            {
              required: true,
              message: '请选择系部',
            },
          ]}
          label="系别"
          placeholder="请选择系部"
        />
        <ProFormDependency name={['deptName']}>
          {({ deptName }) => {
            const data = changeNode(deptName);

            return (
              <ProFormSelect
                options={data}
                debounceTime={1000}
                width="sm"
                rules={[
                  {
                    required: true,
                    message: '请选择专业',
                  },
                ]}
                name="professionalName"
                label="专业"
                placeholder="请选择专业"
              />
            );
          }}
        </ProFormDependency>
        <ProFormDependency name={['professionalName']}>
          {({ professionalName }) => {
            const data = getClassesList(professionalName);

            return (
              <ProFormSelect.SearchSelect
                debounceTime={300}
                options={data}
                width="sm"
                rules={[
                  {
                    required: true,
                    message: '请选择班级',
                  },
                ]}
                name="classes"
                label="班级"
                placeholder="请选择班级"
              />
            );
          }}
        </ProFormDependency>
      </ProForm.Group>
      <ProForm.Group>
        <ProFormSelect
          width="sm"
          name="teacher"
          label="任课教师"
          request={async () => {
            const conditionData = await request(api.getTeacherList, {});

            const list: any[] = [];

            conditionData.data.map((item: professionalType) => {
              list.push({
                label: item.name,
                value: item.id,
              });
            });

            return list;
          }}
          placeholder="请选择任课教师"
          rules={[
            {
              required: true,
              message: '请选择任课教师',
            },
          ]}
        />
        <ProFormSelect
          width="sm"
          name="classStatu"
          label="状态"
          request={async () => {
            const list: any[] = [];

            list.push({
              label: '正在进行',
              value: 1,
            });
            list.push({
              label: '已经节课',
              value: 2,
            });
            list.push({
              label: '其他',
              value: 3,
            });
            return list;
          }}
          placeholder="请选择状态"
          rules={[
            {
              required: true,
              message: '请选择状态',
            },
          ]}
        />
      </ProForm.Group>
    </ModalForm>
  );
};
